﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace WikeSoft.Core.Security
{
    public class DesEncrypt
    {
        public static string Key = "wikesoft";  //密钥
        public static string Iv = "8Fgg1wfSo4XGdMtShbdljwGPj6Bc";   //向量  

        /// <summary>  
        /// 加密  
        /// </summary>  
        /// <param name="data"></param>  
        /// <returns></returns>  
        public static string Encode(string data)
        {



            try
            {
                byte[] btKey = Encoding.UTF8.GetBytes(Key);

                byte[] btIv = Encoding.UTF8.GetBytes(Iv);

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] inData = Encoding.UTF8.GetBytes(data);
                    try
                    {
                        using (
                            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIv),
                                CryptoStreamMode.Write))
                        {
                            cs.Write(inData, 0, inData.Length);

                            cs.FlushFinalBlock();
                        }

                        return Convert.ToBase64String(ms.ToArray());
                    }
                    catch
                    {
                        return data;
                    }
                }
            }
            catch (System.Exception ex)
            {
                return ex.Message;
            } 
            
        }

        /// <summary>  
        /// 解密  
        /// </summary>  
        /// <param name="data"></param>  
        /// <returns></returns>  
        public static string Decode(string data)
        {

            byte[] btKey = Encoding.UTF8.GetBytes(Key);

            byte[] btIv = Encoding.UTF8.GetBytes(Iv);

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] inData = Convert.FromBase64String(data);
                try
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIv), CryptoStreamMode.Write))
                    {
                        cs.Write(inData, 0, inData.Length);

                        cs.FlushFinalBlock();
                    }

                    return Encoding.UTF8.GetString(ms.ToArray());
                }
                catch
                {
                    return data;
                }
            }
        }
    }
}
